package com.yezi.lampcourt.base;

import android.content.Context;
import android.util.Log;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by HongMing Ye
 * on 2017/9/19 0019.
 */

public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {

    private static final String TAG = "BaseObserver";
    private Context mContext;

    protected BaseObserver(Context context) {
        this.mContext = context.getApplicationContext();
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseEntity<T> value) {
        if (value.isSuccess()) {
            T t = value.getData();
            onHandleSuccess(t);
        } else {
            onHandleError(value.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        String errMsg;
        if (e instanceof SocketTimeoutException) {
            errMsg = "网络连接超时，请检查您的网络状态，稍后重试";
        } else if (e instanceof ConnectException) {
            errMsg = "网络连接异常，请检查您的网络状态";
        } else if (e instanceof UnknownHostException) {
            errMsg = "网络异常，请检查您的网络状态";
        } else {
            errMsg = e.getMessage();
        }
        Log.e(TAG, "onError:----" + errMsg);
        onHandleError(errMsg);
    }

    @Override
    public void onComplete() {
        Log.d(TAG, "onComplete");
    }


    protected abstract void onHandleSuccess(T t);

    protected abstract void onHandleError(String msg);
}

